<?php

// 雪里开简易预约制访客管理系统 V1.0（2025.05.20）
// 演示地址: http://fangke.chalide.cn
// 更新关注: /weivote/yuyuefangke
// 文件路径: sys/livi.php
// 文件大小: 14157 字节
// 最后修改时间: 2025-05-20 22:19:29
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
/**
 * 访客列表管理
 * 功能反馈:15058593138@qq.com
 */

// 获取分页参数
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page);
$pageSize = 10;

// 获取搜索参数
$search_field = get_param('search_field', 'vname');
$search_value = get_param('search_value', '');

// 处理AJAX请求
if (isset($_GET['act'])) {
    $db = new MySQLDB();
    
    switch ($_GET['act']) {
        case 'delete':
            // 获取参数
            $id = post_param('id');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 删除数据
            $result = $db->delete('vist', "id = '$id'");
            
            if ($result) {
                json_success('删除成功');
            } else {
                json_error('删除失败：' . $db->getError());
            }
            break;
            
        case 'batch_delete':
            // 获取参数
            $ids = post_param('ids');
            
            // 简单验证
            if (!$ids) {
                json_error('ID不能为空');
            }
            
            // 处理ID参数
            $id_arr = explode(',', $ids);
            $id_arr = array_map('intval', $id_arr);
            $id_str = implode(',', $id_arr);
            
            // 删除数据
            $result = $db->delete('vist', "id IN ($id_str)");
            
            if ($result) {
                json_success('批量删除成功');
            } else {
                json_error('批量删除失败：' . $db->getError());
            }
            break;
            
        case 'detail':
            // 获取参数
            $id = post_param('id');
            
            // 简单验证
            if (!$id) {
                json_error('ID不能为空');
            }
            
            // 查询详情
            $sql = "SELECT v.*, s.name as stu_name, s.xh as stu_xh 
                    FROM `vist` v 
                    LEFT JOIN `stux` s ON v.stuid = s.id 
                    WHERE v.id = '$id'";
            $row = $db->getOne($sql);
            
            if ($row) {
                json_success('获取成功', $row);
            } else {
                json_error('获取失败：记录不存在');
            }
            break;
    }
    exit;
}

// 构建查询条件
$where = '1=1';
if ($search_value) {
    $db = new MySQLDB();
    $search_value = $db->escape($search_value);
    
    switch ($search_field) {
        case 'stu_name':
            $where .= " AND s.name LIKE '%$search_value%'";
            break;
        case 'stu_xh':
            $where .= " AND s.xh LIKE '%$search_value%'";
            break;
        case 'room':
            $where .= " AND v.room LIKE '%$search_value%'";
            break;
        case 'vname':
            $where .= " AND v.vname LIKE '%$search_value%'";
            break;
        case 'vtel':
            $where .= " AND v.vtel LIKE '%$search_value%'";
            break;
        case 'vcode':
            $where .= " AND v.vcode LIKE '%$search_value%'";
            break;
    }
}

// 获取分页数据
$db = new MySQLDB();
$start = ($page - 1) * $pageSize;

// 查询总数
$count_sql = "SELECT COUNT(*) as total 
              FROM `vist` v 
              LEFT JOIN `stux` s ON v.stuid = s.id 
              WHERE $where";
$count_result = $db->getOne($count_sql);
$total = $count_result ? $count_result['total'] : 0;
$totalPage = ceil($total / $pageSize);

// 查询列表
$sql = "SELECT v.*, s.name as stu_name, s.xh as stu_xh 
        FROM `vist` v 
        LEFT JOIN `stux` s ON v.stuid = s.id 
        WHERE $where 
        ORDER BY v.id DESC 
        LIMIT $start, $pageSize";
$list = $db->getAll($sql);

// 加载页头
require_once './inc/head.php';
?>

<div class="container">
    <div class="search-bar">
        <div class="row" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <div class="col-left">
                <h2 style="margin: 0;">访客列表</h2>
            </div>
        </div>
        
        <form action="" method="get" class="search-form" style="display: flex; margin-bottom: 15px;">
            <input type="hidden" name="do" value="livi">
            <select name="search_field" class="search-select">
                <option value="vname" <?php echo $search_field == 'vname' ? 'selected' : ''; ?>>访客姓名</option>
                <option value="vtel" <?php echo $search_field == 'vtel' ? 'selected' : ''; ?>>访客电话</option>
                <option value="stu_name" <?php echo $search_field == 'stu_name' ? 'selected' : ''; ?>>学生姓名</option>
                <option value="stu_xh" <?php echo $search_field == 'stu_xh' ? 'selected' : ''; ?>>学生学号</option>
                <option value="room" <?php echo $search_field == 'room' ? 'selected' : ''; ?>>宿舍号</option>
                <option value="vcode" <?php echo $search_field == 'vcode' ? 'selected' : ''; ?>>访客码</option>
            </select>
            <input type="text" name="search_value" class="search-input" placeholder="请输入搜索内容" value="<?php echo htmlspecialchars($search_value); ?>">
            <button type="submit" class="search-btn">查询</button>
        </form>
    </div>
    
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th width="20"><input type="checkbox" onclick="selectAll(this, 'input[name=ids]')"></th>
                    <th>ID</th>
                    <th>学生信息</th>
                    <th>访客姓名</th>
                    <th>访客电话</th>
                    <th>目标宿舍</th>
                    <th>到访日期</th>
                    <th>访客码</th>
                    <th>核销状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($list)): ?>
                <?php foreach ($list as $item): ?>
                <tr>
                    <td><input type="checkbox" name="ids" value="<?php echo $item['id']; ?>"></td>
                    <td><?php echo $item['id']; ?></td>
                    <td>
                        <?php echo htmlspecialchars($item['stu_name'] ?: '-'); ?><br>
                        <small><?php echo htmlspecialchars($item['stu_xh'] ?: '-'); ?></small>
                    </td>
                    <td><?php echo htmlspecialchars($item['vname']); ?></td>
                    <td><?php echo htmlspecialchars($item['vtel']); ?></td>
                    <td><?php echo htmlspecialchars($item['room']); ?></td>
                    <td><?php echo format_date($item['vdate']); ?></td>
                    <td>
                        <span style="font-weight: bold;"><?php echo htmlspecialchars($item['vcode']); ?></span>
                    </td>
                    <td>
                        <?php if ($item['htime']): ?>
                        <span style="color: green;">已核销</span><br>
                        <small><?php echo format_date($item['htime'], 'Y-m-d H:i'); ?></small>
                        <?php else: ?>
                        <span style="color: orange;">未核销</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <button type="button" class="btn btn-default btn-sm" onclick="showDetail(<?php echo $item['id']; ?>)">详情</button>
                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteRecord(<?php echo $item['id']; ?>, function() { window.location.reload(); })">删除</button>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php else: ?>
                <tr>
                    <td colspan="10" align="center">暂无数据</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($total > 0): ?>
    <div class="table-footer">
        <div class="table-info">共 <?php echo $total; ?> 条记录，第 <?php echo $page; ?>/<?php echo $totalPage; ?> 页</div>
        <div class="table-actions">
            <button type="button" class="btn btn-danger" onclick="batchDelete('ids')">批量删除</button>
        </div>
        <?php echo paginate($page, $totalPage, '?do=livi&search_field=' . urlencode($search_field) . '&search_value=' . urlencode($search_value)); ?>
    </div>
    <?php endif; ?>
</div>

<script>
// 显示详情
function showDetail(id) {
    ajaxRequest('?do=livi&act=detail', {id: id}, function(res) {
        if (res.code === 0) {
            const data = res.data;
            
            let content = `
            <div class="detail-section">
                <h3 class="detail-title">学生信息</h3>
                <div class="detail-item">
                    <div class="detail-label">姓名:</div>
                    <div class="detail-value">${data.stu_name || '-'}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">学号:</div>
                    <div class="detail-value">${data.stu_xh || '-'}</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">访客信息</h3>
                <div class="detail-item">
                    <div class="detail-label">姓名:</div>
                    <div class="detail-value">${data.vname}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">电话:</div>
                    <div class="detail-value">${data.vtel}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">目标宿舍:</div>
                    <div class="detail-value">${data.room}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">到访日期:</div>
                    <div class="detail-value">${formatDate(data.vdate)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">到访事由:</div>
                    <div class="detail-value">${data.reason}</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">访客码</h3>
                <div class="visit-code">${data.vcode}</div>
            </div>
            
            <div class="detail-section">
                <h3 class="detail-title">核销信息</h3>
                ${data.htime ? `
                <div class="detail-item">
                    <div class="detail-label">核销状态:</div>
                    <div class="detail-value"><span style="color: green;">已核销</span></div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">核销时间:</div>
                    <div class="detail-value">${formatDateTime(data.htime)}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">核销账号:</div>
                    <div class="detail-value">${data.huser || '-'}</div>
                </div>
                ` : `
                <div class="detail-item">
                    <div class="detail-label">核销状态:</div>
                    <div class="detail-value"><span style="color: orange;">未核销</span></div>
                </div>
                `}
            </div>
            `;
            
            showMask(content, '访客详情', [
                {
                    text: '关闭',
                    class: 'mask-button-default',
                    click: closeMask
                },
                {
                    text: '删除',
                    class: 'mask-button-danger',
                    click: function() {
                        closeMask();
                        deleteRecord(id, function() {
                            window.location.reload();
                        });
                    }
                }
            ]);
        } else {
            showToast(res.msg, 'error');
        }
    });
}

// 格式化日期
function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0');
}

// 格式化日期时间
function formatDateTime(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.getFullYear() + '-' + 
           String(date.getMonth() + 1).padStart(2, '0') + '-' + 
           String(date.getDate()).padStart(2, '0') + ' ' +
           String(date.getHours()).padStart(2, '0') + ':' +
           String(date.getMinutes()).padStart(2, '0') + ':' +
           String(date.getSeconds()).padStart(2, '0');
}

// 选择全部
function selectAll(checkbox, selector) {
    const items = document.querySelectorAll(selector);
    items.forEach(function(item) {
        item.checked = checkbox.checked;
    });
}
</script>

<style>
.detail-section {
    margin-bottom: 20px;
}
.detail-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #eee;
}
.detail-item {
    display: flex;
    margin-bottom: 8px;
}
.detail-label {
    width: 80px;
    font-weight: bold;
}
.detail-value {
    flex: 1;
}
.table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    padding: 10px 0;
}
.table-info {
    margin-bottom: 10px;
}
.table-actions {
    margin-bottom: 10px;
}
.visit-code {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
    letter-spacing: 2px;
}
</style>
